package com.example.text01

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.AnimationUtils
import android.widget.BaseExpandableListAdapter
import android.widget.ExpandableListView
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

class MainActivity5 : AppCompatActivity() {
    
    // 中国省份数组
    private val provinces = arrayOf(
        "北京市", "上海市", "广东省", "江苏省", "浙江省",
        "四川省", "湖北省", "陕西省", "山东省", "福建省"
    )
    
    // 省份对应的城市数据
    private val provinceCities = hashMapOf(
        "北京市" to arrayOf("东城区", "西城区", "朝阳区", "丰台区", "石景山区", "海淀区", "通州区"),
        "上海市" to arrayOf("黄浦区", "徐汇区", "长宁区", "静安区", "普陀区", "虹口区", "杨浦区", "浦东新区"),
        "广东省" to arrayOf("广州市", "深圳市", "珠海市", "汕头市", "佛山市", "韶关市", "湛江市", "肇庆市", "惠州市"),
        "江苏省" to arrayOf("南京市", "苏州市", "无锡市", "常州市", "镇江市", "南通市", "泰州市", "扬州市", "盐城市"),
        "浙江省" to arrayOf("杭州市", "宁波市", "温州市", "嘉兴市", "湖州市", "绍兴市", "金华市", "台州市", "丽水市"),
        "四川省" to arrayOf("成都市", "绵阳市", "德阳市", "南充市", "宜宾市", "自贡市", "乐山市", "泸州市", "达州市"),
        "湖北省" to arrayOf("武汉市", "宜昌市", "襄阳市", "荆州市", "十堰市", "黄石市", "恩施州", "黄冈市", "咸宁市"),
        "陕西省" to arrayOf("西安市", "宝鸡市", "咸阳市", "铜川市", "渭南市", "延安市", "榆林市", "汉中市", "安康市"),
        "山东省" to arrayOf("济南市", "青岛市", "淄博市", "枣庄市", "东营市", "烟台市", "潍坊市", "济宁市", "威海市"),
        "福建省" to arrayOf("福州市", "厦门市", "莆田市", "三明市", "泉州市", "漳州市", "南平市", "龙岩市", "宁德市")
    )
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main5)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        
        // 初始化ExpandableListView
        setupProvinceExpandableList()
    }
    
    private fun setupProvinceExpandableList() {
        val expandableListView = findViewById<ExpandableListView>(R.id.expandableListView)
        
        // 创建自定义ExpandableListAdapter
        val adapter = ProvinceExpandableAdapter()
        expandableListView.setAdapter(adapter)
        
        Log.d("ExpandableList", "ExpandableListView setup completed")
        Log.d("ExpandableList", "Adapter count: ${adapter.groupCount}")
        
        // 添加丝滑流畅的展开收起动画
        expandableListView.setOnGroupClickListener { parent, v, groupPosition, id ->
            Log.d("ExpandableList", "Group $groupPosition clicked")
            val indicator = v.findViewById<TextView>(R.id.expandIndicator)
            val isExpanded = expandableListView.isGroupExpanded(groupPosition)
            
            if (isExpanded) {
                // 收起动画 - 指示器动画
                val indicatorAnim = AnimationUtils.loadAnimation(this, R.anim.indicator_collapse_animation)
                indicator?.startAnimation(indicatorAnim)
                
                // 为所有子项添加收起动画
                val childCount = adapter.getChildrenCount(groupPosition)
                for (i in 0 until childCount) {
                    val childView = expandableListView.getChildAt(i + 1) // +1 因为第一个是group view
                    if (childView != null) {
                        val collapseAnim = AnimationUtils.loadAnimation(this, R.anim.smooth_collapse_animation)
                        collapseAnim.startOffset = (i * 50).toLong() // 错开动画时间
                        childView.startAnimation(collapseAnim)
                    }
                }
                Log.d("ExpandableList", "Collapsing group $groupPosition with smooth animation")
            } else {
                // 展开动画 - 指示器动画
                val indicatorAnim = AnimationUtils.loadAnimation(this, R.anim.indicator_expand_animation)
                indicator?.startAnimation(indicatorAnim)
                Log.d("ExpandableList", "Expanding group $groupPosition with smooth animation")
            }
            
            false // 让系统处理展开/收起，我们只负责动画
        }
        
        // 监听展开和收起事件，为子项添加动画
        expandableListView.setOnGroupExpandListener { groupPosition ->
            Log.d("ExpandableList", "Group $groupPosition expanded - ${provinces[groupPosition]}")
            
            // 延迟为子项添加展开动画
            expandableListView.postDelayed({
                addExpandAnimationToChildren(expandableListView, groupPosition)
            }, 100)
        }
        
        expandableListView.setOnGroupCollapseListener { groupPosition ->
            Log.d("ExpandableList", "Group $groupPosition collapsed - ${provinces[groupPosition]}")
        }
        
        // 测试：自动展开第一个组
        expandableListView.post {
            Log.d("ExpandableList", "Attempting to expand first group with animation")
            expandableListView.expandGroup(0)
        }
    }
    
    // 为子项添加展开动画 - 优化版本
    private fun addExpandAnimationToChildren(expandableListView: ExpandableListView, groupPosition: Int) {
        val adapter = expandableListView.expandableListAdapter as ProvinceExpandableAdapter
        val childCount = adapter.getChildrenCount(groupPosition)
        
        Log.d("ExpandableList", "Adding expand animation for $childCount children in group $groupPosition")
        
        // 使用Handler延迟执行动画，确保子项已经渲染
        expandableListView.postDelayed({
            // 直接通过Adapter获取子视图并添加动画
            for (i in 0 until childCount) {
                expandableListView.postDelayed({
                    try {
                        // 尝试查找子视图
                        for (j in 0 until expandableListView.childCount) {
                            val childView = expandableListView.getChildAt(j)
                            // 检查是否是我们要的子项视图
                            if (childView?.findViewById<TextView>(R.id.cityName) != null) {
                                val cityNameView = childView.findViewById<TextView>(R.id.cityName)
                                val expectedCityName = provinceCities[provinces[groupPosition]]?.get(i)
                                
                                if (cityNameView.text == expectedCityName) {
                                    // 找到匹配的子视图，添加动画
                                    childView.animate()
                                        .alpha(1.0f)
                                        .scaleX(1.0f)
                                        .scaleY(1.0f)
                                        .translationY(0f)
                                        .setDuration(400)
                                        .setStartDelay((i * 80).toLong())
                                        .setInterpolator(android.view.animation.OvershootInterpolator())
                                        .start()
                                    
                                    // 额外的震动效果
                                    childView.postDelayed({
                                        val shakeAnim = AnimationUtils.loadAnimation(this@MainActivity5, R.anim.shake_entrance_animation)
                                        childView.startAnimation(shakeAnim)
                                    }, (i * 80 + 200).toLong())
                                    
                                    break
                                }
                            }
                        }
                    } catch (e: Exception) {
                        Log.e("ExpandableList", "Error animating child $i: ${e.message}")
                    }
                }, (i * 50).toLong())
            }
        }, 200) // 等待展开完成
    }
    
    // 自定义ExpandableListAdapter类
    private inner class ProvinceExpandableAdapter : BaseExpandableListAdapter() {
        
        override fun getGroupCount(): Int {
            val count = provinces.size
            Log.d("ExpandableList", "getGroupCount: $count")
            return count
        }
        
        override fun getChildrenCount(groupPosition: Int): Int {
            val count = provinceCities[provinces[groupPosition]]?.size ?: 0
            Log.d("ExpandableList", "getChildrenCount for ${provinces[groupPosition]}: $count")
            return count
        }
        
        override fun getGroup(groupPosition: Int): Any = provinces[groupPosition]
        
        override fun getChild(groupPosition: Int, childPosition: Int): Any {
            return provinceCities[provinces[groupPosition]]?.get(childPosition) ?: ""
        }
        
        override fun getGroupId(groupPosition: Int): Long = groupPosition.toLong()
        
        override fun getChildId(groupPosition: Int, childPosition: Int): Long = childPosition.toLong()
        
        override fun hasStableIds(): Boolean = false
        
        override fun isChildSelectable(groupPosition: Int, childPosition: Int): Boolean = true
        
        override fun getGroupView(groupPosition: Int, isExpanded: Boolean, convertView: View?, parent: ViewGroup?): View {
            val view = convertView ?: LayoutInflater.from(this@MainActivity5).inflate(R.layout.group_province_item, parent, false)
            
            val provinceName = view.findViewById<TextView>(R.id.provinceName)
            val provinceIcon = view.findViewById<TextView>(R.id.provinceIcon)
            val cityCount = view.findViewById<TextView>(R.id.cityCount)
            val expandIndicator = view.findViewById<TextView>(R.id.expandIndicator)
            
            // 设置省份名称
            provinceName.text = provinces[groupPosition]
            
            // 设置城市数量
            val count = provinceCities[provinces[groupPosition]]?.size ?: 0
            cityCount.text = count.toString()
            
            // 设置省份图标
            val provinceIcons = arrayOf("🏙️", "🌆", "🏞️", "🏢", "🌊", "⛰️", "🌿", "🏠", "🌾", "🌸")
            provinceIcon.text = provinceIcons[groupPosition % provinceIcons.size]
            
            // 设置展开指示器
            expandIndicator.rotation = if (isExpanded) 180f else 0f
            
            // 添加触摸反馈效果
            view.setOnTouchListener { v, event ->
                when (event.action) {
                    android.view.MotionEvent.ACTION_DOWN -> {
                        val hoverAnim = AnimationUtils.loadAnimation(this@MainActivity5, R.anim.group_hover_animation)
                        v.startAnimation(hoverAnim)
                    }
                    android.view.MotionEvent.ACTION_UP, android.view.MotionEvent.ACTION_CANCEL -> {
                        val normalAnim = AnimationUtils.loadAnimation(this@MainActivity5, R.anim.group_normal_animation)
                        v.startAnimation(normalAnim)
                    }
                }
                false // 让事件继续传递
            }
            
            return view
        }
        
        override fun getChildView(groupPosition: Int, childPosition: Int, isLastChild: Boolean, convertView: View?, parent: ViewGroup?): View {
            val view = convertView ?: LayoutInflater.from(this@MainActivity5).inflate(R.layout.child_city_item, parent, false)
            
            val cityName = view.findViewById<TextView>(R.id.cityName)
            val cityIcon = view.findViewById<TextView>(R.id.cityIcon)
            val cityIndex = view.findViewById<TextView>(R.id.cityIndex)
            
            // 设置城市名称
            val city = provinceCities[provinces[groupPosition]]?.get(childPosition)
            cityName.text = city ?: "Unknown City"
            
            // 设置城市编号
            cityIndex.text = String.format("%02d", childPosition + 1)
            
            // 设置城市图标
            val cityIcons = arrayOf("🏙️", "🏢", "🌆", "🌃", "🎡", "⛩️", "🌉", "🏰", "🌸")
            cityIcon.text = cityIcons[childPosition % cityIcons.size]
            
            // 初始化时设置透明度，等待动画触发
            view.alpha = 0.0f
            view.scaleX = 0.3f
            view.scaleY = 0.3f
            
            return view
        }
    }
}